package gateway.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class HttpResponseMapper {
  public void map(ResponseEntity<byte[]> responseEntity, HttpServletResponse response) throws IOException {
    setStatus(responseEntity, response);
    setHeaders(responseEntity, response);
    setBody(responseEntity, response);
  }
  
  private void setStatus(ResponseEntity<byte[]> responseEntity, HttpServletResponse response) {
    response.setStatus(responseEntity.getStatusCode().value());
  }
  
  private void setHeaders(ResponseEntity<byte[]> responseEntity, HttpServletResponse response) {
    responseEntity.getHeaders().forEach((name, values) -> {
      // 尽可能将所有响应头都转发
      if (!CollectionUtils.isEmpty(values)&&!"Transfer-Encoding".equals(name)) {
        response.addHeader(name, values.get(0));
      }
    });
  }
  
  /**
   * 把结果写回客户端
   *
   * @param responseEntity
   * @param response
   * @throws IOException
   */
  private void setBody(ResponseEntity<byte[]> responseEntity, HttpServletResponse response) throws IOException {
    if (responseEntity.getBody() != null) {
      response.getOutputStream().write(responseEntity.getBody());
    }
  }
}
